<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="签约主体" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入签约主体"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会计" prop="accountantId">
        <el-select v-model="queryParams.accountantId" placeholder="请选择会计" clearable filterable>
          <el-option
            v-for="item in accountantList"
            :key="item.userId"
            :label="item.nickName+'('+item.phonenumber+')'"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['signMain:signMain:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['signMain:signMain:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['signMain:signMain:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['signMain:signMain:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          plain-->
      <!--          icon="el-icon-upload2"-->
      <!--          size="mini"-->
      <!--          @click="handleImport"-->
      <!--          v-hasPermi="['companyAgreement:companyAgreement:import']"-->
      <!--        >导入</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="signMainList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" align="center" width="50"/>
      <el-table-column label="签约主体" align="center" prop="name"/>
      <el-table-column label="地点" align="center" prop="fullAddress"/>
      <el-table-column label="会计" align="center" prop="accountName"/>
      <el-table-column label="附加税率(%)" align="center" prop="additionalTaxRate"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column prop="status" label="启用状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_enable_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['signMain:signMain:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['signMain:signMain:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改签约主体对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <!--        <el-form-item label="注册地" prop="allAddress" label-width="80px" >-->
        <!--          <el-cascader v-model="form.allAddress" :options="city" :disabled="false" @change="setAllAddress" :props="{ checkStrictly: true }" placeholder="请选择省市" clearable filterable >-->
        <!--            <template slot-scope="{ node, data }">-->
        <!--              <span > {{ data.label }}</span>-->
        <!--              <span v-if="!node.children"> ({{ data.children }}) </span>-->
        <!--            </template>-->
        <!--          </el-cascader>-->
        <!--        </el-form-item>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约主体" prop="name">
              <el-input v-model="form.name" placeholder="请输入签约主体名称" style="width: 400px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="注册地" prop="allAddress">
              <el-cascader v-model="form.allAddress" :options="cityAddress" @change="setAllAddress" placeholder="请选择省市"
                           style="width: 400px" clearable filterable>
                <template slot-scope="{ node, data }">
                  <span> {{ data.label }}</span>
                  <span v-if="!node.children"> ({{ data.children }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="附加税率(%)" prop="additionalTaxRate">
              <el-input v-model="form.additionalTaxRate" placeholder="请输入附加税率，例如：5" type="number"
                        style="width: 400px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="会计" prop="accountantId">
              <el-select v-model="form.accountantId" placeholder="请选择会计人员" style="width: 400px" clearable filterable>
                <el-option
                  v-for="item in accountantList"
                  :key="item.userId"
                  :label="item.nickName+'('+item.phonenumber+')'"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item label="养老保险缴费比例%（企业）" prop="yangLaoPayProportionEtp">
              <el-input v-model="form.yangLaoPayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="（个人）" prop="yangLaoPayProportionPsn">
              <el-input v-model="form.yangLaoPayProportionPsn" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item label="医疗保险缴费比例%（企业）" prop="yiLiaoPayProportionEtp">
              <el-input v-model="form.yiLiaoPayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="（个人）" prop="yiLiaoPayProportionPsn">
              <el-input v-model="form.yiLiaoPayProportionPsn" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item label="失业保险缴费比例%（企业）" prop="shiYePayProportionEtp">
              <el-input v-model="form.shiYePayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="（个人）" prop="shiYePayProportionPsn">
              <el-input v-model="form.shiYePayProportionPsn" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工伤保险缴费比例%（企业）" prop="gongShangPayProportionEtp">
              <el-input v-model="form.gongShangPayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="生育保险缴费比例%（企业）" prop="shengYuPayProportionEtp">
              <el-input v-model="form.shengYuPayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item label="公积金缴费比例%（企业）" prop="afPayProportionEtp">
              <el-input v-model="form.afPayProportionEtp" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="（个人）" prop="afPayProportionPsn">
              <el-input v-model="form.afPayProportionPsn" placeholder="请输入附加税率"
                        onkeyup="this.value= this.value.match(/\d/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                        style="width: 150px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="启用状态" prop="status">
          <el-select
            style="width: 400px"
            v-model="form.status"
            placeholder="默认启用"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_enable_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 签约主体导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的签约主体数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listSignMain, getSignMain, delSignMain, addSignMain, updateSignMain} from "@/api/sign_main/signmain";
import {getUserListByRoleKey} from "@/api/system/user";
import {getAddressTree} from "@/api/system/area";
import {getToken} from "@/utils/auth";

export default {
  name: "SignMain",
  dicts: ['sys_enable_status'],
  data() {

    // var validateAddress = (rule, value, callback) => {
    //   if (value.length > 2) {
    //     callback(new Error('只需精确到市'))
    //   } else {
    //     callback()
    //   }
    // }

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中name数组
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 签约主体表格数据
      signMainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 财务人员
      accountantList: [],
      // 查询参数
      queryParams: {
        orderByColumn: 'create_time',
        isAsc: 'desc',
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        registerProvince: null,
        registerCity: null,
        accountantId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "主体公司名称不能为空", trigger: "blur"}
        ],
        allAddress: [
          {required: true, message: "注册地不能为空", trigger: "blur"},
          // { trigger: "blur", validator:validateAddress}
        ],
        // accountantId: [
        //   { required: true, message: "财务人员不能为空", trigger: "blur" }
        // ],
        // additionalTaxRate: [
        //   { required: true, message: "附加税率不能为空", trigger: "blur" }
        // ],
      },
      cityAddress: [],
      // 签约主体导入参数
      upload: {
        // 是否显示弹出层（签约主体导入）
        open: false,
        // 弹出层标题（签约主体导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的签约主体数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/signMain/signMain/importData"
      },
    };
  },
  created() {
    this.getList();
    this.getAccountList();
    this.getCityTree();
  },
  methods: {
    /** 查询签约主体列表 */
    getList() {
      this.loading = true;
      listSignMain(this.queryParams).then(response => {
        this.signMainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderByColumn: 'm.create_time',
        isAsc: 'desc',
        id: null,
        name: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        allAddress: null,
        registerProvince: null,
        registerCity: null,
        accountantId: null,
        additionalTaxRate: null,
        yangLaoPayProportionEtp: null,
        yangLaoPayProportionPsn: null,
        yiLiaoPayProportionEtp: null,
        yiLiaoPayProportionPsn: null,
        shiYePayProportionEtp: null,
        shiYePayProportionPsn: null,
        gongShangPayProportionEtp: null,
        shengYuPayProportionEtp: null,
        afPayProportionEtp: null,
        afPayProportionPsn: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加签约主体";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSignMain(id).then(response => {
        this.form = response.data;
        this.form.allAddress = []
        this.form.allAddress.push(response.data.registerProvince)
        this.form.allAddress.push(response.data.registerCity)
        this.open = true;
        this.title = "修改签约主体";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.allAddress != null) {
              this.form.registerProvince = this.form.allAddress[0];
              this.form.registerCity = this.form.allAddress[1];
            }
            updateSignMain(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.allAddress != null) {
              this.form.registerProvince = this.form.allAddress[0];
              this.form.registerCity = this.form.allAddress[1];
            }
            addSignMain(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal.confirm('确定删除签约主体为"' + names + '"的数据项？').then(function () {
        return delSignMain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('signMain/signMain/export', {
        ...this.queryParams
      }, `signMain_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "签约主体导入";
      this.upload.open = true;
    },
    //获取地点树
    getCityTree() {
      getAddressTree("2").then(response => {
        if (response.code === 200) {
          // console.log(response.data)
          this.cityAddress = response.data;
        }
      });
    },
    /** 获取地址 */
    setAllAddress(item) {
      // console.log(item)
      this.$set(this.form, 'allAddress', item)
    },
    //获取财务人员id
    getAccountList() {
      var array = [];
      array.push("accountant");
      array.push("accountantmanagment");
      getUserListByRoleKey("accountant").then(response => {
        if (response.code === 200) {
          this.accountantList = response.data;
        }
      });
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('signMain/signMain/importTemplate', {}, `signMain_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.updateSupport = 0;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 100vh;padding: 10px 10px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
